/* 充电桩应答中心合法用户认证通过信息命令*/
exports.run = (info, core, socket, logger) => {
  let redis = core.getService('redis').getClient();
  const reader = new core.BufferReader(info.data);
  let userIdBuf = reader.read(2),
    cmdIndexBuf = reader.read(2),
    typeBuf = reader.read(1),
    cardNumberBuf = reader.read(16),
    centerTransactionIdBuf = reader.read(15),
    appointmentNo = reader.read(20),
    charging = reader.read(8),
    cartVIN = reader.read(17),
    cartNo = reader.read(8),
    startSOC = reader.read(1),
    endSOC = reader.read(1),
    chargeCumulative = reader.read(2),
    chargeEnergyCumulative = reader.read(2),
    chargingTime = reader.read(4),
    chargeStrategy = reader.read(1),
    chargeStrategyParameters = reader.read(2),
    endsNormally = reader.read(1),
    startDate = reader.read(8),
    endDate = reader.read(8),
    transactionDate = reader.read(8),
    startChargingDegree = reader.read(4),
    endChargingDegree = reader.read(4);
  let data = {
    type: typeBuf.readUInt8(),
    card: cardNumberBuf.toString().replace(/\0/g, ''),
    number: centerTransactionIdBuf.toString().replace(/\0/g, ''),
    serial: charging.toString('hex').replace(/^0+/, ''),
    stsoc: startSOC.readUInt8(),
    sesoc: endSOC.readUInt8(),
    power: chargeCumulative.readUInt16LE(), // 充电量
    realPower: chargeEnergyCumulative.readUInt16LE() * 0.01, // 充电量
    length: chargingTime.readUInt32LE(),
    strategy: chargeStrategy.readUInt8(),
    param: chargeStrategyParameters.readUInt16LE(),
    isn: endsNormally.readUInt8(),
    setime: core.date.buffer2Date(endDate).unix(),
    stmeter: startChargingDegree.readUInt32LE() * 0.01,
    semeter: endChargingDegree.readUInt32LE() * 0.01,
  }
  logger.info(data);
  // 防止 重复取消
  redis.setex(`stop:${data.serial}`, [30, data.number]);
  core.getService('sdk').endCharging(data)
    .then((response) => {
      let data = response.data;
      logger.info(data);
      let customerNumber = Buffer.alloc(30);
      let settleTimeAndCharging = Buffer.alloc(12);
      let settlementChargeFee = Buffer.alloc(12);
      let serviceFee = Buffer.alloc(12);
      let consumptionAmount = Buffer.alloc(12);
      settlementChargeFee.write(`${data.feprice || '0'}`);
      serviceFee.write(`${data.seprice || '0'}`);
      consumptionAmount.write(`${data.price || '0'}`);
      socket.sendCommands(0x68, core.concat([
        userIdBuf,
        cmdIndexBuf,
        typeBuf,
        cardNumberBuf,
        customerNumber,
        settleTimeAndCharging,
        settlementChargeFee,
        serviceFee,
        consumptionAmount,
        centerTransactionIdBuf,
        transactionDate,
      ]));
    }).catch((err) => logger.error(err));
}
